<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller
{
	function __construct()
	{
		parent::__construct();
	}
	
	function index()
	{
		$this->load->view('login');
	}
	
	function check()
	{
		$config = array(
			array(
				'field' => "email",
				'label' => "E-mail",
				'rules' => "trim|required|min_length[3]|max_length[150]|valid_email|xss_clean"
			),
			array(
				'field' => "senha",
				'label' => "Senha",
				'rules' => "trim|required|min_length[3]|max_length[45]|xss_clean"
			)
		);
		
		$this->form_validation->set_rules($config);
		
		if ($this->form_validation->run() == FALSE)
		{
			$this->index();
			echo "err#".validation_errors();
			exit;
		}
		else
		{	
			$objectSearch = null;
			
			$objectSearch->groupOp = "AND";
			$objectSearch->rules[0]->op = "eq";
			$objectSearch->rules[0]->field = "email";
			$objectSearch->rules[0]->data = strtolower($this->input->post('email'));
			
			$objectSearch->rules[1]->op = "eq";
			$objectSearch->rules[1]->field = "senha";
			$objectSearch->rules[1]->data = $this->input->post('senha');
			
			$usuario = $this->generic_model->getByFilter($objectSearch, "usuarios");
			
			if (!is_null($usuario) && count($usuario) > 0)
			{
				if ($usuario[0]->flag_ativo == "N" || $usuario[0]->flag_deletado == "S")
				{
					$this->index();
					echo "err#Usu&aacute;rio sem acesso!<br>Entre em contato com o administrador do sistema!";
					exit;
				}
				else
				{
					$user = array(
									'v_id_usuario' => $usuario[0]->id,
									'v_nome_usuario' => $usuario[0]->nome,
									'v_email_usuario' => $usuario[0]->email,
									'loggedin' => TRUE
								);
					$this->session->set_userdata($user);
					echo "oks#";
					exit;
				}
			}
			else
			{
				$this->index();
				echo "err#Usu&aacute;rio / Senha Inv&aacute;lidos!";
				exit;
			}
		}		
	}
	
	function logout()
	{
		$this->session->sess_destroy();
		redirect(base_url(), "refresh");
	}	
}